import { Context } from 'koa';
import { Middleware, KoaMiddlewareInterface } from 'routing-controllers';

/**
 * 全局中间件
 * 自定义日志处理中间件
 * 前置路由鉴权(优先级比全局拦截器高，即设置时先于拦截器执行)
 */
@Middleware({ type: 'before' })
export class RequestMiddleware implements KoaMiddlewareInterface {
  async use(context: Context, next: (err?: any) => Promise<any>): Promise<any> {
    const { request, response } = context;
    // if (!unless(request.url)) {
    //   const token = context.cookies.get('login_auth') || request.header['authorization'];
    //   const payload:any = verfiy(token);
    //   console.log(payload, context.path);
    //   request.query.id = payload.id;
    // }
    await next();
  }
}

@Middleware({ type: 'after' })
export class ResponseMiddleware implements KoaMiddlewareInterface {
  async use(context: Context, next: (err?: any) => Promise<any>): Promise<any> {
    const { request, response } = context;
    console.log(`${request.method} ${request.url} [${response.message}]\n`);
    await next();
  }
}
